<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>服务管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div slot="header">
        <span>服务来源配置</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-circle-plus-outline"
          @click="addColumn"
        >
          新增来源
        </el-button>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="id" label="来源规则ID" width="100px">
        </el-table-column>
        <el-table-column prop="service_id" label="服务名称【ID】">
          <template>
            {{ this.$route.query.name }}【{{ this.$route.query.id }}】
          </template>
        </el-table-column>
        <el-table-column prop="source_rule" label="来源规则">
          <template slot-scope="scope">
            <div v-if="scope.row.editRowVisible || scope.row.lookSave">
              <el-select
                v-model="scope.row.source_rule"
                placeholder="请选择"
                filterable
                clearable
                @change="changeRule(scope.row.index)"
                size="mini"
              >
                <el-option
                  key="0"
                  label="全国"
                  :value="typeof scope.row.source_rule == 'string' ? 0 + '' : 0"
                ></el-option>
                <el-option
                  key="1"
                  label="省份"
                  :value="typeof scope.row.source_rule == 'string' ? 1 + '' : 1"
                ></el-option>
                <el-option
                  key="2"
                  label="城市"
                  :value="typeof scope.row.source_rule == 'string' ? 2 + '' : 2"
                ></el-option>
              </el-select>
            </div>
            <div v-else>
              <span v-if="scope.row.source_rule === 1">省份</span>
              <span v-else-if="scope.row.source_rule === 2">城市</span>
              <span v-else>全国</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="range_value" label="规则范围">
          <template slot-scope="scope">
            <div v-if="scope.row.editRowVisible || scope.row.lookSave">
              <el-input
                v-model="scope.row.range_name"
                placeholder="请选择"
                readonly
                size="mini"
              >
                <el-button
                  slot="append"
                  icon="el-icon-setting"
                  @click="openPC(scope.row.index)"
                ></el-button>
              </el-input>
              <el-input
                v-model="scope.row.range_value"
                v-show="false"
              ></el-input>
            </div>
            <div v-else>{{ scope.row.range_name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="provider_ids" label="供应商">
          <template slot-scope="scope">
            <div v-if="scope.row.editRowVisible || scope.row.lookSave">
              <el-select
                v-model="scope.row.provider_ids"
                placeholder="请选择"
                filterable
                clearable
                multiple
                collapse-tags
                size="mini"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="item in providerList"
                  :key="item.provider_id"
                  :label="
                    item.provider_short_name + '【' + item.provider_id + '】'
                  "
                  :value="item.provider_id + ''"
                >
                </el-option>
              </el-select>
            </div>
            <div v-else>{{ scope.row.provider_name }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="status.name"
          label="状态"
          width="100px"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope" v-if="scope.row.id">
            <el-link
              type="primary"
              @click="scope.row.editRowVisible = true"
              v-show="!scope.row.editRowVisible"
            >
              编辑
            </el-link>
            <el-link
              type="primary"
              @click="saveRow(scope.row)"
              v-show="scope.row.editRowVisible"
            >
              保存
            </el-link>
            &nbsp;
            <el-link
              type="danger"
              v-show="
                scope.row.status.id == 1 &&
                scope.row.source_rule != 0 &&
                !scope.row.editRowVisible
              "
              @click="disable(scope.row.id)"
            >
              关闭
            </el-link>
            <el-link
              type="primary"
              v-show="scope.row.status.id == 0 && !scope.row.editRowVisible"
              @click="enable(scope.row)"
            >
              开启
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-button @click="$router.push('/project/Service')">取 消</el-button>
        <el-button
          class="theme-background-color"
          @click="saveSourceInfo"
          v-show="saveNum != 0"
          >保 存</el-button
        >
      </el-row>
    </el-card>

    <!-- 选择省份区域对话框 -->
    <chooseMultipleProvince
      :provinceVisible.sync="provinceVisible"
      :checkedRanges="checkedRanges"
      @showProvincesData="updateRanges"
    ></chooseMultipleProvince>

    <!-- 选择城市区域对话框 -->
    <ChooseMultipleCity
      :cityVisible.sync="cityVisible"
      :checkedRanges="checkedRanges"
      @showCitiesData="updateRanges"
    ></ChooseMultipleCity>
  </div>
</template>

<script>
import chooseMultipleProvince from '../region/ChooseMultipleProvince.vue'
import ChooseMultipleCity from '../region/ChooseMultipleCity.vue'

export default {
  components: { chooseMultipleProvince, ChooseMultipleCity },
  data() {
    return {
      // 源数据
      tableData: [],
      providerList: [],
      service_id: '',
      // 省市控件勾选用的数据
      checkedRanges: [],
      provinceVisible: false,
      cityVisible: false,
      activeIndex: '',
      saveNum: 0
    }
  },
  created() {
    this.service_id = this.$route.query.id
    this.getAllProducts()
    this.getAllSource()
  },
  methods: {
    async getAllProducts() {
      const url = '/admin/ServiceSystem/getServiceProvider'
      const { data: res } = await this.$http.post(url, {
        service_type: this.$route.query.service_type,
        relation_id: this.$route.query.relation_id
      })
      this.providerList = res.data
    },
    // 获取服务所有来源
    async getAllSource() {
      const url = '/admin/ServiceSystem/getServiceSource'
      const { data: res } = await this.$http.post(url, {
        service_id: this.service_id
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].editRowVisible = false
      }
      this.tableData = res.data
    },
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    addColumn() {
      this.saveNum++
      this.tableData.push({
        id: '',
        service_id: this.$route.query.id,
        name: this.$route.query.name,
        source_rule: '',
        range_name: '',
        range_value: '',
        rule_range: [],
        provider_ids: [],
        provider_name: '',
        status: '',
        editRowVisible: false,
        lookSave: true
      })
    },
    changeRule(index) {
      if (
        this.tableData[index].source_rule === 0 ||
        this.tableData[index].source_rule === '0'
      ) {
        this.tableData[index].range_name = '全国'
        this.tableData[index].range_value = '全国'
        this.tableData[index].rule_range = []
      } else {
        this.tableData[index].range_name = ''
        this.tableData[index].range_value = ''
        this.tableData[index].rule_range = []
      }
    },
    openPC(index) {
      if (this.tableData[index].source_rule === '') {
        this.$message({
          message: '请先选择来源规则',
          type: 'warning'
        })
      } else if (parseInt(this.tableData[index].source_rule) !== 0) {
        if (parseInt(this.tableData[index].source_rule) === 1) {
          this.provinceVisible = true
        }
        if (parseInt(this.tableData[index].source_rule) === 2) {
          this.cityVisible = true
        }
        this.activeIndex = index
        // console.log(this.tableData[index])
        this.checkedRanges = this.tableData[index].rule_range
      }
    },
    updateRanges(data) {
      this.tableData[this.activeIndex].range_value = data.code.join(',')
      this.tableData[this.activeIndex].range_name = data.name.join(',')
      this.tableData[this.activeIndex].rule_range = data.code
      console.log(data)
    },
    async disable(id) {
      const { data: res } = await this.$http.post(
        '/admin/ServiceSystem/onOffStatus',
        { config_id: id, status: 0 }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].editRowVisible = false
      }
      this.tableData = res.data
      this.getAllSource()
    },
    async enable(row) {
      // 校验是否能开启
      const flag = this.validatorRow(row, '，开启失败')
      if (!flag) return

      const { data: res } = await this.$http.post(
        '/admin/ServiceSystem/onOffStatus',
        { config_id: row.id, status: 1 }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].editRowVisible = false
      }
      this.tableData = res.data
      this.getAllSource()
    },
    saveError() {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].editRowVisible) {
          return this.$message.error('有未保存的服务来源,请先保存')
        }
      }
    },
    // 保存来源信息
    async saveSourceInfo() {
      const saveErrors = this.saveError()
      if (saveErrors) return
      const postData = this.filterPostData()
      // 保存和校验编辑状态下的和新增的数据
      const flag = this.validTable(postData)
      if (!flag) return
      const { data: res } = await this.$http.post(
        '/admin/ServiceSystem/addSource',
        {
          data: postData
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].editRowVisible = false
      }
      this.tableData = res.data
      this.getAllSource()
      this.saveNum = 0
    },
    async saveRow(row) {
      // 校验数据
      const flag = this.validatorRow(row)
      if (!flag) return

      const { data: res } = await this.$http.post(
        '/admin/ServiceSystem/editSource',
        { row }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].editRowVisible = false
      }
      this.tableData = res.data
      this.getAllSource()
    },
    filterPostData() {
      // 1、先找出编辑状态下的，或者新增的数据（没有id的）
      var postData = []
      for (let i = 0; i < this.tableData.length; i++) {
        if (
          (this.tableData[i].editRowVisible || this.tableData[i].lookSave) &&
          !(
            this.tableData[i].source_rule === '' &&
            this.tableData[i].rule_range.length === 0 &&
            this.tableData[i].provider_ids.length === 0
          )
        ) {
          postData.push(this.tableData[i])
        }
      }
      return postData
    },
    validTable(postData) {
      // 表格整体提交校验
      // 2、校验必填项
      for (let i = 0; i < postData.length; i++) {
        if (postData[i].source_rule === '') {
          this.$message.error(
            '请选择第' + (postData[i].index + 1) + '行的来源规则'
          )
          return false
        } else if (postData[i].range_value === '') {
          this.$message.error(
            '请选择第' + (postData[i].index + 1) + '行的规则范围'
          )
          return false
        } else if (postData[i].provider_ids.length === 0) {
          this.$message.error(
            '请选择第' + (postData[i].index + 1) + '行的供应商'
          )
          return false
        }
      }
      // 3、校验重复规则
      for (let i = 0; i < postData.length; i++) {
        for (let j = 0; j < this.tableData.length; j++) {
          if (
            !(
              postData[i].id !== '' && postData[i].id === this.tableData[j].id
            ) &&
            parseInt(postData[i].source_rule) ===
              this.tableData[j].source_rule &&
            parseInt(this.tableData[j].status.id) === 1
          ) {
            console.log(this.tableData[j])
            // 校验无id的和有id不等于自己的,来源规则相同，状态开启的
            if (this.tableData[j].source_rule === 0) {
              // 来源规则是全国
              this.$message.error(
                '第' + (postData[i].index + 1) + '行的只能有一个全国的来源规则'
              )
              return false
            } else {
              // 来源规则是省市
              if (
                postData[i].rule_range.sort(this.sortNumber).toString() ===
                this.tableData[j].rule_range.sort(this.sortNumber).toString()
              ) {
                this.$message.error(
                  '第' + (postData[i].index + 1) + '行的规则范围不能重复'
                )
                return false
              } else if (
                postData[i].provider_ids.sort(this.sortNumber).toString() ===
                this.tableData[j].provider_ids.sort(this.sortNumber).toString()
              ) {
                this.$message.error(
                  '第' + (postData[i].index + 1) + '行的供应商不能重复'
                )
                return false
              }
            }
          }
        }
      }
      return true
    },
    validatorRow(row, openWarning = '') {
      // 表格行编辑校验
      // 校验必填项
      // console.log(row)
      if (!openWarning) {
        if (row.source_rule === '') {
          this.$message.error('请选择来源规则')
          return false
        } else if (row.range_value === '') {
          this.$message.error('请选择规则范围')
          return false
        } else if (row.provider_ids.length === 0) {
          this.$message.error('请选择供应商')
          return false
        }
      }
      for (let i = 0; i < this.tableData.length; i++) {
        // 如果来源规则相同，id不相等并且是开启状态下的规则则校验
        if (
          row.source_rule === this.tableData[i].source_rule &&
          row.id !== this.tableData[i].id &&
          parseInt(this.tableData[i].status.id) === 1
        ) {
          if (this.tableData[i].source_rule === 0) {
            // 来源规则是全国
            this.$message.error('只能有一个全国的来源规则' + openWarning)
            return false
          } else {
            // 来源规则是省市
            if (
              row.rule_range.sort(this.sortNumber).toString() ===
              this.tableData[i].rule_range.sort(this.sortNumber).toString()
            ) {
              this.$message.error('规则范围不能重复' + openWarning)
              return false
            } else if (
              row.provider_ids.sort(this.sortNumber).toString() ===
              this.tableData[i].provider_ids.sort(this.sortNumber).toString()
            ) {
              this.$message.error('供应商不能重复' + openWarning)
              return false
            }
          }
        }
      }
      return true
    },
    sortNumber(a, b) {
      return a - b
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  min-width: 100px;
  margin: 5px 0px 5px 10px;
}
</style>
